//package com.xry.test1.service.impl;
//
//import com.fasterxml.jackson.databind.JsonNode;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.xry.test1.model.AirData;
//import com.xry.test1.service.IHomeService;
//import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.messaging.simp.SimpMessagingTemplate;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Service;
//
//import java.time.LocalDateTime;
//
//@Service
//public class AirServiceImpl implements IHomeService {
//    @Autowired
//    private SimpMessagingTemplate messagingTemplate; // WebSocket 消息推送
//
//    @Autowired
//    private MQTTSubscribe mqttSubscribe; // MQTT 订阅
//
//    //private Integer lastMessage = -1; // 记录上一次的消息，避免重复推送
//    //private AirData lastAirData = new AirData();
//
//    /**
//     * 每秒查询一次 MQTT 数据并推送到前端
//     */
//

//
//    @Scheduled(fixedRate = 1000) // 每秒执行一次
//    public void checkAndPushMqttMessage(){
//        try {
//            //mqttSubscribe.subscribeToTopic("kitchenGas"); // 订阅主题
//            String message = mqttSubscribe.waitForMessage(); // 等待消息
//            AirData airData = new AirData();
//            //int messageInt = Integer.parseInt(message);
//            ObjectMapper objectMapper = new ObjectMapper();
//            JsonNode jsonNode = objectMapper.readTree(message);
//            int messageInt = jsonNode.get("temp").asInt();
//            airData.setTemp(messageInt);
//            messageInt = jsonNode.get("hum").asInt();
//            airData.setHum(messageInt);
//
//
//            // 只有数据发生变化时才推送，避免重复推送相同数据
//
//            airData.setDate(LocalDateTime.now().toString());
//            messagingTemplate.convertAndSend("/topic/airData", airData);
//            System.out.println("推送 WebSocket 数据：" + airData);
//
//        } catch (Exception e) {
//            System.out.println("MQTT 获取数据失败air：" + e.getMessage());
//        }
//    }
//}

package com.xry.test1.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xry.test1.dao.AirRepository;
import com.xry.test1.model.AirData;
import com.xry.test1.service.IHomeService;
import com.xry.test1.service.MQTTSubscriber.MQTTSubscribe;
import com.xry.test1.service.MQTTSubscriber.MqttMessageHandler;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import jakarta.annotation.PostConstruct;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class AirServiceImpl implements IHomeService, MqttMessageHandler {

    @Autowired
    private SimpMessagingTemplate messagingTemplate; // WebSocket 消息推送

    @Autowired
    private MQTTSubscribe mqttSubscribe; // MQTT 订阅

    private static final String AIR_TOPIC = "temp_and_hum"; // 只订阅 airData 主题


    private Integer lastTemp=0;

    @Autowired
    private AirRepository airRepository;

    @PostConstruct
    public void init() {
        mqttSubscribe.subscribeToTopic(AIR_TOPIC,this);
        //System.out.println("✅ AirService 已订阅主题：" + AIR_TOPIC);
    }

    public int getLastTemp() {
        return lastTemp;
    }

    public void handleIncomingMessage(String topic, MqttMessage message) {
        if (!AIR_TOPIC.equals(topic)) {
            return; // 过滤掉非 airData 的消息
        }

        try {
            String payload = new String(message.getPayload());
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(payload);

            int temp = jsonNode.get("temp").asInt();
            int hum = jsonNode.get("hum").asInt();

            System.out.println("temp: " + temp);
            System.out.println("hum: " + hum);

            AirData airData = new AirData();
            airData.setTemp(temp);
            airData.setHum(hum);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            airData.setDate(LocalDateTime.now().format(formatter));

            airRepository.save(airData);
            // 推送数据到 WebSocket
            messagingTemplate.convertAndSend("/topic/airData", airData);
            System.out.println("推送 WebSocket 数据：" + airData);


            lastTemp=temp;


        } catch (Exception e) {
            System.out.println("air 解析 MQTT 消息失败：" + e.getMessage());
        }
    }
}

